﻿using Newtonsoft.Json;
using BaoShouTangServer.ApiModels;
using BaoShouTangServer.Models;
using BaoShouTangServer.Service;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Runtime.InteropServices;

using UFIDA.U8.MomServiceCommon;
using UFIDA.U8.U8MOMAPIFramework;
using UFIDA.U8.U8APIFramework;
using UFIDA.U8.U8APIFramework.Meta;
using UFIDA.U8.U8APIFramework.Parameter;
using MSXML2;
using Microsoft.Ajax.Utilities;
using System.Reflection.Emit;
using BaoShouTangServer.DTOModel;

namespace BaoShouTangServer.ApiServies
{
    public class PU_ArrivalVouchService
    {
        public static string 生成采购到货(U8Login.clsLogin u8Login, DTOPO_Pomain dtoPO_Pomain, PO_Pomain pomain, ref string 到货单接口返回result)
        {
            //第二步：构造环境上下文对象，传入login，并按需设置其它上下文参数
            U8EnvContext envContext = new U8EnvContext();
            envContext.U8Login = u8Login;

            //设置上下文参数
            envContext.SetApiContext("VoucherType", "2"); //上下文数据类型：int，含义：单据类型， 采购到货单 2 
            envContext.SetApiContext("bPositive", true); //上下文数据类型：bool，含义：红蓝标识：True,蓝字；False,红字
            envContext.SetApiContext("sBillType", "0"); //上下文数据类型：string，含义：到货单类型， 到货单 0 退货单 1
            envContext.SetApiContext("sBusType", "普通采购"); //上下文数据类型：string，含义：业务类型：普通采购,直运采购,受托代销

            //第三步：设置API地址标识(Url)
            //当前API：添加新单据的地址标识为：U8API/MaterialOut/Add
            U8ApiAddress myApiAddress = new U8ApiAddress("U8API/ArrivedGoods/VoucherSave");



            //第四步：构造APIBroker
            U8ApiBroker broker = new U8ApiBroker(myApiAddress, envContext);



            //给BO表头参数DomHead赋值，此BO参数的业务类型为材料出库单，属表头参数。BO参数均按引用传递
            //提示：给BO表头参数DomHead赋值有两种方法

            DataTable Dt_data = new DataTable();

            DbHelperSQL.connectionString = u8Login.UFDataConnstringForNet;
            StringBuilder strMsg = new StringBuilder();
            StringBuilder Strsql = new StringBuilder();

            //创建临时表
            string StrHeadName = "tempdb..pu_ArrHead" + Guid.NewGuid().ToString().Replace("-", "");
            string StrBodyName = "tempdb..pu_ArrBody" + Guid.NewGuid().ToString().Replace("-", "");
            Strsql.Append(" select  top 0  * into " + StrHeadName + " from pu_ArrHead Where 1=1");
            Strsql.Append(" \n select  top 0  *  into " + StrBodyName + " from pu_ArrBody Where 1=1");
            DbHelperSQL.ExecuteSql(Strsql.ToString());
            int id = (int)SnowFlakeSingle.Instance.NextId();
            int zpurRkdHead = 到货单头赋值(StrHeadName, id, pomain, dtoPO_Pomain);
            int zpurRkdTailList = 到货单体赋值(StrBodyName, id, pomain, dtoPO_Pomain);
            //塞入临时表

            Strsql = new StringBuilder();
            Strsql.Append("select editprop='A',* from " + StrHeadName);
            DOMDocument domHead = Pub.getDom(Strsql.ToString(), u8Login.UfDbName);
            Strsql = new StringBuilder();
            Strsql.Append("select editprop='A',* from " + StrBodyName);
            DOMDocument domBody = Pub.getDom(Strsql.ToString(), u8Login.UfDbName);

            Strsql = new StringBuilder();
            Strsql.Append(" if not object_id('" + StrHeadName + "') is null drop table " + StrHeadName);
            Strsql.Append(" if not object_id('" + StrBodyName + "') is null drop table " + StrBodyName);

            DbHelperSQL.ExecuteSql(Strsql.ToString());

            broker.AssignNormalValue("DomHead", domHead);
            //方法一是直接传入MSXML2.DOMDocumentClass对象
            broker.AssignNormalValue("domBody", domBody);


            //给普通参数VoucherState赋值。此参数的数据类型为int，此参数按值传递，表示单据状态：2新增，1修改，0非编辑
            broker.AssignNormalValue("VoucherState", 2);

            //该参数CurDom为OUT型参数，由于其数据类型为MSXML2.IXMLDOMDocument2，非一般值类型，因此必须传入一个参数变量。在API调用返回时，可以直接使用该参数
            MSXML2.DOMDocument CurDom = new MSXML2.DOMDocument();
            broker.AssignNormalValue("CurDom", CurDom);
            //给普通参数UserMode赋值。此参数的数据类型为int，此参数按值传递，表示模式，0：CS;1:BS
            broker.AssignNormalValue("UserMode", 0);


            //第六步：调用API
            if (!broker.Invoke())
            {
                //错误处理
                Exception apiEx = broker.GetException();
                if (apiEx != null)
                {
                    if (apiEx is MomSysException)
                    {
                        MomSysException sysEx = apiEx as MomSysException;
                        到货单接口返回result = ("系统异常：" + sysEx.Message);
                        //todo:异常处理
                    }
                    else if (apiEx is MomBizException)
                    {
                        MomBizException bizEx = apiEx as MomBizException;
                        到货单接口返回result = ("API异常：" + bizEx.Message);
                        //todo:异常处理
                    }
                    //异常原因
                    String exReason = broker.GetExceptionString();
                    if (exReason.Length != 0)
                    {
                        到货单接口返回result = ("异常原因：" + exReason);
                    }
                }
                //结束本次调用，释放API资源
                broker.Release();
            }

            //第七步：获取返回结果

            //获取返回值
            //获取普通返回值。此返回值数据类型为System.String，此参数按值传递，表示错误描述：空，正确；非空，错误
            System.String result = broker.GetReturnValue() as System.String;
            到货单接口返回result = result;
            //获取普通OUT参数curID。此返回值数据类型为string，在使用该参数之前，请判断是否为空
            string curIDRet = broker.GetResult("curID") as string;
            //获取普通OUT参数CurDom。此返回值数据类型为MSXML2.IXMLDOMDocument2，在使用该参数之前，请判断是否为空
            //MSXML2.IXMLDOMDocument2 CurDomRet = Convert.ToObject(broker.GetResult("CurDom"));
            //到货单接口返回result += JsonConvert.SerializeObject(broker.GetResult("CurDom"));

            //结束本次调用，释放API资源
            broker.Release();
            return curIDRet;

        }

        private static int 到货单体赋值(string strBodyName, int id, PO_Pomain pomain,  DTOPO_Pomain dtoPO_Pomain)
        {
            int result = 0;
            for (int i = 0; i < dtoPO_Pomain.dtoPO_Podetails.Count; i++)
            {
                PO_Podetails podetail = SqlSugarHelp.scope.Queryable<PO_Podetails>().Where(it => it.POID == dtoPO_Pomain.POID && it.ID == dtoPO_Pomain.dtoPO_Podetails[i].ID).First();
                if (podetail == null)
                {
                    throw new NullReferenceException($"根据{dtoPO_Pomain.dtoPO_Podetails[i].ID}未找到采购订单行，可能采购重做了订单。请重新申请质检");
                }

                Inventory inventory = SqlSugarHelp.scope.Queryable<Inventory>().Where(it => it.cInvCode == podetail.cInvCode).First();
                pu_arrbody pu_arrbody = new pu_arrbody();
                pu_arrbody.id = id;
                pu_arrbody.cwhcode = inventory.cDefWareHouse;
                //仓库名
                pu_arrbody.cwhname = "";
                pu_arrbody.autoid = (int)SnowFlakeSingle.Instance.NextId(); 
                pu_arrbody.cinvcode = podetail.cInvCode;
                //存货代码
                pu_arrbody.cinvaddcode = inventory.cInvAddCode;
                //存货名称
                pu_arrbody.cinvname = inventory.cInvName;
                pu_arrbody.cinvstd = inventory.cInvStd;
                pu_arrbody.cinvccode = inventory.cInvCCode;
                //	pu_arrbody.cunitid	="NULL";
                pu_arrbody.ccomunitcode = inventory.cComUnitCode;
                //主计量  PCS
                pu_arrbody.cinvm_unit = "";
                pu_arrbody.igrouptype = inventory.iGroupType;
                pu_arrbody.cgroupcode = inventory.cGroupCode;
                //	pu_arrbody.cinva_unit	="NULL";
                pu_arrbody.bservice = inventory.bService;
                //	pu_arrbody.iinvexchrate	="NULL";
                pu_arrbody.binvbatch = inventory.bInvBatch;
                if (inventory.bInvBatch)
                {
                    //批号
                    pu_arrbody.cbatch = dtoPO_Pomain.dtoPO_Podetails[i].cbatch;
                }
                
                //	pu_arrbody.dvdate	="NULL";
                //	pu_arrbody.dpdate	="NULL";
                //	pu_arrbody.imassdate	="NULL";
                //	pu_arrbody.cmassunit	="NULL";
                //	pu_arrbody.cgspstate	="NULL";
                //	pu_arrbody.ccloser	="NULL";
                //原币含税单价 
                pu_arrbody.ioritaxcost = podetail.iTaxPrice;
                //	pu_arrbody.icorid	="NULL";
                pu_arrbody.iquantity = dtoPO_Pomain.dtoPO_Podetails[i].qualifiedQuantity;
                //	pu_arrbody.inum	="NULL";
                //原币单价
                pu_arrbody.ioricost = podetail.iUnitPrice;

                //原币价税合计  先去掉
                pu_arrbody.iorisum = pu_arrbody.ioritaxcost * pu_arrbody.iquantity;
                //原币金额   先去掉
                pu_arrbody.iorimoney = pu_arrbody.iorisum / (1 + podetail.iPerTaxRate.GetValueOrDefault() / 100);

                //原币税额  先去掉
                pu_arrbody.ioritaxprice = pu_arrbody.iorisum - pu_arrbody.iorimoney;

                //本币单价 
                pu_arrbody.icost = podetail.iUnitPrice;
                //本币金额 先去掉
                pu_arrbody.imoney = pu_arrbody.iorimoney;
                //本币税额  先去掉
                pu_arrbody.itaxprice = pu_arrbody.ioritaxprice;
                //本币价税合计  先去掉 等于原币家虽合计
                pu_arrbody.isum = pu_arrbody.iorisum;
                pu_arrbody.cbcloser = "";

                if (inventory.bFree1 == true)
                {
                    pu_arrbody.cfree1 = "采购";
                }
                //if (rdrecord10Service.是否启用存货自由项统货拣货次数(inventory.cInvCode))
                //{
                //    var list = rdrecord10Service.获取所有自由项统货拣货次数(inventory.cInvCode);
                //    if (list != null && list.Count > 0)
                //    {
                //        pu_arrbody.cfree1 = list.First().cUDValue;
                //    }
                    
                //}

                //	pu_arrbody.cfree1	="NULL";
                //	pu_arrbody.cfree2	="NULL";
                //	pu_arrbody.cdefine22	="NULL";
                //	pu_arrbody.cdefine23	="NULL";
                //	pu_arrbody.cdefine24	="NULL";
                //	pu_arrbody.cdefine25	="NULL";
                //	pu_arrbody.cdefine26	="NULL";
                //	pu_arrbody.cdefine27	="NULL";
                //	pu_arrbody.cdefine28	="NULL";
                //	pu_arrbody.cdefine29	="NULL";
                //  pu_arrbody.cdefine30 = "";
                //	pu_arrbody.cdefine31	="NULL";
                //	pu_arrbody.cdefine32	="NULL";
                //	pu_arrbody.cdefine33	="NULL";
                //	pu_arrbody.cdefine34	="NULL";
                //	pu_arrbody.cdefine35	="NULL";
                //	pu_arrbody.cdefine36	="NULL";
                //	pu_arrbody.cdefine37	="NULL";
                pu_arrbody.itaxrate = podetail.iPerTaxRate.GetValueOrDefault();
                //	pu_arrbody.citemcode	="NULL";
                //	pu_arrbody.citemname	="NULL";
                //	pu_arrbody.citem_class	="NULL";
                //	pu_arrbody.citem_name	="NULL";
                pu_arrbody.iposid = podetail.ID;
                //字典写的不合格数量，但是U8里不合格数量是0.先当合格数量用
                pu_arrbody.fvalidquantity = dtoPO_Pomain.dtoPO_Podetails[i].qualifiedQuantity;
                //字典写的不合格件数 ，但是看着像件数。
                pu_arrbody.fvalidnum = 0;
                //字典写的 不合格入库数量  不合格数量先去掉
                //pu_arrbody.fvalidinquan = dtoPO_Pomain.dtoPO_Podetails[i].UnqualifiedQuantity;
                //	pu_arrbody.fvalidinnum	="NULL";
                //	pu_arrbody.fkpquantity	="NULL";
                //	pu_arrbody.finvalidquantity	="NULL";
                //	pu_arrbody.finvalidnum	="NULL";
                //字典写的 不合格品入库数量  
                pu_arrbody.finvalidinquan = 0;
                //字典写的 已拒收数量 
                pu_arrbody.fretquantity = 0;
                //	pu_arrbody.frefusequantity	="NULL";
                //	pu_arrbody.frefusenum	="NULL";
                //实收数量 
                pu_arrbody.frealquantity = dtoPO_Pomain.dtoPO_Podetails[i].qualifiedQuantity;
                //实收件数 
                pu_arrbody.frealnum = 0;
                //	pu_arrbody.cfree3	="NULL";
                //	pu_arrbody.cfree4	="NULL";
                //	pu_arrbody.cfree5	="NULL";
                //	pu_arrbody.cfree6	="NULL";
                //	pu_arrbody.cfree7	="NULL";
                //	pu_arrbody.cfree8	="NULL";
                //	pu_arrbody.cfree9	="NULL";
                //	pu_arrbody.cfree10	="NULL";
                pu_arrbody.cinvdefine1 = "";
                pu_arrbody.cinvdefine2 = "";
                pu_arrbody.cinvdefine3 = "";
                pu_arrbody.cinvdefine4 = "";
                pu_arrbody.cinvdefine5 = "";
                pu_arrbody.cinvdefine6 = "";
                //	pu_arrbody.cinvdefine7	="NULL";
                //	pu_arrbody.cinvdefine8	="NULL";
                //	pu_arrbody.cinvdefine9	="NULL";
                //pu_arrbody.cinvdefine10 = "";
                //	pu_arrbody.cinvdefine11	="NULL";
                //	pu_arrbody.cinvdefine12	="NULL";
                //	pu_arrbody.cinvdefine13	="NULL";
                //	pu_arrbody.cinvdefine14	="NULL";
                //	pu_arrbody.cinvdefine15	="NULL";
                //	pu_arrbody.cinvdefine16	="NULL";
                //拒收来源 
                pu_arrbody.rejectsource = false;
                //是否检验 
                pu_arrbody.bgsp = (int)podetail.bGsp;
                //	pu_arrbody.cinvauthid	="NULL";
                pu_arrbody.btaxcost = (bool)podetail.bTaxCost;
                //是否已报检  数据库查出来是0 ，不知道填什么，先按0
                pu_arrbody.binspect = 0;
                //	pu_arrbody.contractrowguid	="NULL";
                //	pu_arrbody.iinvmpcost	="NULL";
                pu_arrbody.irowno = i+1;
                if (podetail.SoType != null)
                {
                    //int.TryParse(podetail.SoType.ToString(), out int r);
                    pu_arrbody.sotype = (int)podetail.SoType;
                }
                pu_arrbody.csocode = podetail.csocode;
                //pu_arrbody.cdemandmemo = "NULL";
                if (podetail.iordertype != null)
                {
                    pu_arrbody.iordertype = (int)podetail.iordertype;
                }
                
                pu_arrbody.csoordercode = podetail.csoordercode;
                pu_arrbody.iorderseq = podetail.iorderseq;
                pu_arrbody.iorderdid = podetail.iorderdid;
                //	pu_arrbody.ippartid	="NULL";
                //	pu_arrbody.ipquantity	="NULL";
                //	pu_arrbody.iptoseq	="NULL";
                //	pu_arrbody.cveninvcode	="NULL";
                //	pu_arrbody.cveninvname	="NULL";
                pu_arrbody.sodid = podetail.SoDId;
                pu_arrbody.cordercode = pomain.cPOID;
                //是否急料  采购订单里没有这个字段，不知道填什么，先按0
                pu_arrbody.bexigency = 0;
                //	pu_arrbody.contractcode	="NULL";
                //	pu_arrbody.contractrowno	="NULL";
                //	pu_arrbody.fretnum	="NULL";
                //	pu_arrbody.fsumrefusequantity	="NULL";
                //	pu_arrbody.fsumrefusenum	="NULL";
                //	pu_arrbody.fdtquantity	="NULL";
                //	pu_arrbody.finvalidinnum	="NULL";
                //	pu_arrbody.finspectquantity	="NULL";
                //	pu_arrbody.finspectnum	="NULL";
                //单据状态 先根据查出来的数据填
                pu_arrbody.vouchstate = 0;
                //报检数量  数据库查出来有值200，接口没查到。先空着试试
                //pu_arrbody.fininquantity = "200.000000";
                //	pu_arrbody.fininnum	="NULL";
                //	pu_arrbody.dValidateDate	="NULL";
                //报检换算率  查出来是0
                pu_arrbody.inspecexchrate = 0;
                //	pu_arrbody.irejectautoid	="NULL";
                //、、有效期推算方式 查出来是0
                pu_arrbody.iexpiratdatecalcu = 0;
                //	pu_arrbody.cexpirationdate	="NULL";
                //	pu_arrbody.dexpirationdate	="NULL";
                //	pu_arrbody.carrivalcode	="NULL";
                //	pu_arrbody.cbatchproperty1	="NULL";
                //	pu_arrbody.cbatchproperty2	="NULL";
                //	pu_arrbody.cbatchproperty3	="NULL";
                //	pu_arrbody.cbatchproperty4	="NULL";
                //	pu_arrbody.cbatchproperty5	="NULL";
                //	pu_arrbody.cbatchproperty6	="NULL";
                //	pu_arrbody.cbatchproperty7	="NULL";
                //	pu_arrbody.cbatchproperty8	="NULL";
                //	pu_arrbody.cbatchproperty9	="NULL";
                //	pu_arrbody.cbatchproperty10	="NULL";
                //	pu_arrbody.cupsocode	="NULL";
                pu_arrbody.ivouchrowno = podetail.ivouchrowno;
                pu_arrbody.cbmemo = dtoPO_Pomain.dtoPO_Podetails[i].到货单备注;
                //单据行条码 查出来 "||pudh|0000008996|1" 先空着  不是从采购订单来的
                //pu_arrbody.cbsysbarcode = "||pudh|0000008996|1";
                //产出品类型 字典没查到，数据库查到是0
                pu_arrbody.iproducttype = 0;
                //	pu_arrbody.cmaininvcode	="NULL";
                //	pu_arrbody.imainmodetailsid	="NULL";
                //	pu_arrbody.isourcemocode	="NULL";
                //	pu_arrbody.isourcemodetailsid	="NULL";
                //	pu_arrbody.freworkquantity	="NULL";
                //	pu_arrbody.freworknum	="NULL";
                //	pu_arrbody.fsumreworkquantity	="NULL";
                //	pu_arrbody.fsumreworknum	="NULL";
                pu_arrbody.planlotnumber = podetail.planlotnumber;
                pu_arrbody.bgift = podetail.bgift;
                //	pu_arrbody.dlineclosedate	="NULL";
                //	pu_arrbody.cfactorycode	="NULL";
                //	pu_arrbody.cfactoryname	="NULL";

                result += pu_arrbody.Add(strBodyName);

            }
            return result;
        }

        private static int 到货单头赋值(string strHeadName, int id, PO_Pomain pomain, DTOPO_Pomain dtoPO_Pomain)
        {
            pu_ArrHead pu_ArrHead = new pu_ArrHead();

            //单据模版号 
            pu_ArrHead.ivtid = 8169;
            //时间戳 
            //pu_ArrHead.ufts = "                    26465.7091";
            pu_ArrHead.ddate = DateTime.Parse(dtoPO_Pomain.入库日期.ToString("yyyy-MM-dd"));
            pu_ArrHead.id = id;
            pu_ArrHead.ccode = getPU_ArrivalVouchMaxCode(dtoPO_Pomain.入库日期.ToString("yyyy-MM-dd"));
            //pu_ArrHead.ccode = "0000000009"; 
            pu_ArrHead.cptcode = pomain.cPTCode;
            pu_ArrHead.cptname = pomain.cBusType;
            pu_ArrHead.cvencode = pomain.cVenCode;
            //供应商名称
            pu_ArrHead.cvenabbname = "";
            pu_ArrHead.cvenname = "";
            pu_ArrHead.cdepcode = pomain.cDepCode;
            //部门名称
            pu_ArrHead.cdepname = "";
            pu_ArrHead.cpocode = pomain.cPOID;
            //	pu_ArrHead.cpersoncode="NULL";
            //	pu_ArrHead.cpersonname="NULL";
            //	pu_ArrHead.cpaycode="NULL";
            //	pu_ArrHead.cpayname="NULL";
            pu_ArrHead.cexch_name = pomain.cexch_name;
            //币种 RMB
            pu_ArrHead.cexch_code = "";
            //汇率
            pu_ArrHead.iexchrate = 1;
            //	pu_ArrHead.cmemo="NULL";
            pu_ArrHead.cbustype = pomain.cBusType;
            pu_ArrHead.cmaker = dtoPO_Pomain.cUser_Name;
            //负发票标志 不知道是啥，数据库是0
            pu_ArrHead.bnegative = 0;
            //	pu_ArrHead.ccloser="NULL";
            //扣税类别
            pu_ArrHead.idiscounttaxtype = pomain.iDiscountTaxType;
            //	pu_ArrHead.cdefine1="NULL";
            //	pu_ArrHead.cdefine2="NULL";
            //	pu_ArrHead.cdefine3="NULL";
            //	pu_ArrHead.cdefine4="NULL";
            //	pu_ArrHead.cdefine5="NULL";
            //	pu_ArrHead.cdefine6="NULL";
            //	pu_ArrHead.cdefine7="NULL";
            //	pu_ArrHead.cdefine8="NULL";
            //	pu_ArrHead.cdefine9="NULL";
            //	pu_ArrHead.cdefine10="NULL";
            //	pu_ArrHead.cdefine11="NULL";
            //	pu_ArrHead.cdefine12="NULL";
            //	pu_ArrHead.cdefine13="NULL";
            //	pu_ArrHead.cdefine14="NULL";
            //	pu_ArrHead.cdefine15="NULL";
            //	pu_ArrHead.cdefine16="NULL";
            pu_ArrHead.itaxrate = (decimal?)pomain.iTaxRate;
            //	pu_ArrHead.csccode="NULL";
            //	pu_ArrHead.cscname="NULL";
            //	pu_ArrHead.cauthid="NULL";
            //	pu_ArrHead.cvendefine1="NULL";
            //	pu_ArrHead.cvendefine2="NULL";
            //	pu_ArrHead.cvendefine3="NULL";
            //	pu_ArrHead.cvendefine4="NULL";
            //	pu_ArrHead.cvendefine5="NULL";
            //	pu_ArrHead.cvendefine6="NULL";
            //	pu_ArrHead.cvendefine7="NULL";
            //	pu_ArrHead.cvendefine8="NULL";
            //	pu_ArrHead.cvendefine9="NULL";
            //	pu_ArrHead.cvendefine10="NULL";
            //	pu_ArrHead.cvendefine11="NULL";
            //	pu_ArrHead.cvendefine12="NULL";
            //	pu_ArrHead.cvendefine13="NULL";
            //	pu_ArrHead.cvendefine14="NULL";
            //	pu_ArrHead.cvendefine15="NULL";
            //	pu_ArrHead.cvendefine16="NULL";
            //(0到货单,1退货单,2拒收单) 
            pu_ArrHead.ibilltype = 0;
            //	pu_ArrHead.cvouchtype="NULL";
            //pu_ArrHead.cmaketime = DateTime.Now;
            //pu_ArrHead.cmodifytime = DateTime.Now;
            //pu_ArrHead.cmodifydate = DateTime.Now;
            //修改人 
            pu_ArrHead.creviser = dtoPO_Pomain.cUser_Name;
            //	pu_ArrHead.cauditdate="NULL";
            //	pu_ArrHead.caudittime="NULL";
            //	pu_ArrHead.cverifier="NULL";
            //审核状态 
            pu_ArrHead.iverifystateex = 0;
            //	pu_ArrHead.ireturncount="NULL";
            //是否启用工作流 
            pu_ArrHead.iswfcontrolled = false;
            //	pu_ArrHead.cvenpuomprotocol="NULL";
            //	pu_ArrHead.cvenpuomprotocolname="NULL";
            //	pu_ArrHead.cchanger="NULL";
            //	pu_ArrHead.dclosedate="NULL";
            pu_ArrHead.cvoucherstate = "开立";
            //流程ID 
            pu_ArrHead.iflowid = 0;
            //	pu_ArrHead.cflowname="NULL";
            //	pu_ArrHead.bflowprocess="NULL";
            //bstoragearrivalorder  不知道是啥
            pu_ArrHead.bstoragearrivalorder = 1;
            //打印次数 
            pu_ArrHead.iprintcount = 0;
            //条码号先空着试试
            //pu_ArrHead.csysbarcode = "||pudh|0000008996";
            //	pu_ArrHead.ccurrentauditor="NULL";


            return pu_ArrHead.Add(strHeadName);
        }

        //获取材料出库单最大号
        private static string getPU_ArrivalVouchMaxCode(string 入库日期)
        {
            string sql = $@"select  isnull(max(right(cCode,4)),'0000') from PU_ArrivalVouch
						 where DATEDIFF(MONTH,dDate ,'{入库日期}') = 0";
            string code = SqlSugarHelp.scope.Ado.GetString(sql);
            if (string.IsNullOrWhiteSpace(code) == false)
            {
                int.TryParse(code, out int a);
                if (a > 0)
                {
                    a++;
                    code =  "QC"+ DateTime.Now.ToString("yyMM") + a.ToString().PadLeft(6, '0'); ;
                }
                else
                {
                    code = "QC" + DateTime.Now.ToString("yyMM") + 1.ToString().PadLeft(6, '0');
                }
            }
            else
            {
                code = "QC" + DateTime.Now.ToString("yyyyMMdd") + 1.ToString().PadLeft(6, '0');
            }
            return code;
        }

        public static string 审核到货单审核(U8Login.clsLogin u8Login, string id,ref string result)
        {
            //第二步：构造环境上下文对象，传入login，并按需设置其它上下文参数
            U8EnvContext envContext = new U8EnvContext();
            envContext.U8Login = u8Login;

            //采购所有接口均支持内部独立事务和外部事务，默认内部事务
            //如果是外部事务，则需要传递ADO.Connection对象，并将IsIndependenceTransaction属性设置为false
            //envContext.BizDbConnection = new ADO.Connection();
            //envContext.IsIndependenceTransaction = false;

            //设置上下文参数
            envContext.SetApiContext("VoucherType", "2"); //上下文数据类型：int，含义：单据类型，采购到货单 2 
            envContext.SetApiContext("bPositive", true); //上下文数据类型：bool，含义：红蓝标识：True,蓝字；False,红字
            envContext.SetApiContext("sBillType", "0"); //上下文数据类型：string，含义：到货单类型， 到货单 0 退货单 1
            envContext.SetApiContext("sBusType", "普通采购"); //上下文数据类型：string，含义：业务类型：普通采购,直运采购,受托代销

            //第三步：设置API地址标识(Url)
            //当前API：审核采购到货单的地址标识为：U8API/ArrivedGoods/ConfirmArr
            U8ApiAddress myApiAddress = new U8ApiAddress("U8API/ArrivedGoods/ConfirmArr");

            //第四步：构造APIBroker
            U8ApiBroker broker = new U8ApiBroker(myApiAddress, envContext);

            DataTable Dt_data = new DataTable();

            DbHelperSQL.connectionString = u8Login.UFDataConnstringForNet;
            StringBuilder Strsql = new StringBuilder();


            //塞入临时表

            Strsql = new StringBuilder();
            Strsql.Append("select * from pu_ArrHead where id = '" + id + "'");
            DOMDocument domHead = Pub.getDom(Strsql.ToString(), u8Login.UfDbName);

            DbHelperSQL.ExecuteSql(Strsql.ToString());
            broker.AssignNormalValue("domHead", domHead);

            //第六步：调用API
            if (!broker.Invoke())
            {
                //错误处理
                Exception apiEx = broker.GetException();
                if (apiEx != null)
                {
                    if (apiEx is MomSysException)
                    {
                        MomSysException sysEx = apiEx as MomSysException;
                        result = ("系统异常：" + sysEx.Message);
                        //todo:异常处理
                    }
                    else if (apiEx is MomBizException)
                    {
                        MomBizException bizEx = apiEx as MomBizException;
                        result = ("API异常：" + bizEx.Message);
                        //todo:异常处理
                    }
                    //异常原因
                    String exReason = broker.GetExceptionString();
                    if (exReason.Length != 0)
                    {
                        result = ("异常原因：" + exReason);
                    }
                }
                //结束本次调用，释放API资源
                broker.Release();
                return result;
            }
            //第七步：获取返回结果

            //获取返回值
            //获取普通返回值。此返回值数据类型为System.String，此参数按值传递，表示错误描述：空，正确；非空，错误
             result = broker.GetReturnValue() as System.String;

            //结束本次调用，释放API资源
            broker.Release();
            return result;

        }

        public static string 弃审到货单(U8Login.clsLogin u8Login, string id, ref string result)
        {
            //第二步：构造环境上下文对象，传入login，并按需设置其它上下文参数
            U8EnvContext envContext = new U8EnvContext();
            envContext.U8Login = u8Login;

            //采购所有接口均支持内部独立事务和外部事务，默认内部事务
            //如果是外部事务，则需要传递ADO.Connection对象，并将IsIndependenceTransaction属性设置为false
            //envContext.BizDbConnection = new ADO.Connection();
            //envContext.IsIndependenceTransaction = false;

            //设置上下文参数
            envContext.SetApiContext("VoucherType", "2"); //上下文数据类型：int，含义：单据类型，采购到货单 2 
            envContext.SetApiContext("bPositive", true); //上下文数据类型：bool，含义：红蓝标识：True,蓝字；False,红字
            envContext.SetApiContext("sBillType", "0"); //上下文数据类型：string，含义：到货单类型， 到货单 0 退货单 1
            envContext.SetApiContext("sBusType", "普通采购"); //上下文数据类型：string，含义：业务类型：普通采购,直运采购,受托代销

            //第三步：设置API地址标识(Url)
            //当前API：审核采购到货单的地址标识为：U8API/ArrivedGoods/ConfirmArr
            U8ApiAddress myApiAddress = new U8ApiAddress("U8API/ArrivedGoods/CancelconfirmArr");

            //第四步：构造APIBroker
            U8ApiBroker broker = new U8ApiBroker(myApiAddress, envContext);

            DataTable Dt_data = new DataTable();

            DbHelperSQL.connectionString = u8Login.UFDataConnstringForNet;
            StringBuilder Strsql = new StringBuilder();


            //塞入临时表

            Strsql = new StringBuilder();
            Strsql.Append("select * from pu_ArrHead where id = '" + id + "'");
            DOMDocument domHead = Pub.getDom(Strsql.ToString(), u8Login.UfDbName);

            DbHelperSQL.ExecuteSql(Strsql.ToString());
            broker.AssignNormalValue("domHead", domHead);

            //第六步：调用API
            if (!broker.Invoke())
            {
                //错误处理
                Exception apiEx = broker.GetException();
                if (apiEx != null)
                {
                    if (apiEx is MomSysException)
                    {
                        MomSysException sysEx = apiEx as MomSysException;
                        result = ("系统异常：" + sysEx.Message);
                        //todo:异常处理
                    }
                    else if (apiEx is MomBizException)
                    {
                        MomBizException bizEx = apiEx as MomBizException;
                        result = ("API异常：" + bizEx.Message);
                        //todo:异常处理
                    }
                    //异常原因
                    String exReason = broker.GetExceptionString();
                    if (exReason.Length != 0)
                    {
                        result = ("异常原因：" + exReason);
                    }
                }
                //结束本次调用，释放API资源
                broker.Release();
                return result;
            }
            //第七步：获取返回结果

            //获取返回值
            //获取普通返回值。此返回值数据类型为System.String，此参数按值传递，表示错误描述：空，正确；非空，错误
            result = broker.GetReturnValue() as System.String;

            //结束本次调用，释放API资源
            broker.Release();
            return result;

        }
    }
}